<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车</title>
  <link rel="stylesheet" href="../css/10.css">
</head>

<body>
  全选：<input type="checkbox" name="" id="isAll" onchange="allChangeHandler(this)">
  总价：<span id="all-price"></span>
  总数量：<span id="all-num"></span>

  <button onclick="delSelechHandler()">删除所选</button>
  <button onclick="clearHandler()">清空购物车</button>

  <ul class="clist">
    <!-- <li>
      <input type="checkbox" id="" name="">
      <h2></h2>
      <p>单价：</p>
      <p>小计：</p>
      <button>删除</button>
      <button>-</button>
      <input type="text" name="" id="">
      <button>+</button>
    </li> -->
  </ul>
  <script src="../js/axios.js"></script>

  <script type="module">
    let baseURL = "http://localhost:3000"
    axios.defaults.baseURL = baseURL;
    let token = localStorage.getItem('token')
    // console.log(token);
    axios.defaults.headers.common['Authorization'] = "bearer " + token;
    let pagesize = 1000;
    let cartAPI = '/api/front/carts'

    let productArr = [];

    showCartNum()
    async function showCartNum() {
      let r = await axios.get(cartAPI, { params: { pagesize } })
      console.log(r.data.data);
      // 方法1
      // let arr = r.data.data.map(()=>`
      // <li>
      //     <input type="checkbox" id="" name="">
      //     <h2></h2>
      //     <p>单价：</p>
      //     <p>小计：</p>
      //     <button>删除</button>
      //     <button>-</button>
      //     <input type="text" name="" id="">
      //     <button>+</button>
      // </li>
      // `)
      // document.querySelector('.clist').innerHTML = arr.join('')

      // 方法2
      productArr = [...r.data.data]
      // console.log(productArr);
      let liArr = productArr.map(v => `
            <li>
                <a href="${v.pid.click_url}">
                  <img src="${v.pid.pict_url}" alt="">
                </a>
                <input type="checkbox" id="" name="" ${v.checked ? 'checked' : ''} onchange="changeHandler('${v._id}',this)">
                <h2>${v.pid.title}</h2>
                <p>单价：${v.pid.real_wap_price}</p>
                <p>小计：${v.pid.real_wap_price * v.pnum}</p>
                <button onclick="cartDelHandler('${v._id}')">删除</button>
                <button onclick="cartSub('${v._id}')">-</button>
                <input type="text" name="" id="" value="${v.pnum}">
                <button onclick="cartAdd('${v._id}')">+</button>
            </li>
            `)
      document.querySelector('.clist').innerHTML = liArr.join('')

      // 处理总价和总数
      let isAll = productArr.every(v => v.checked == true)
      console.log(isAll);
      if (productArr.length == 0) {
        isAll = false
      }
      let isAllIpt = document.querySelector('#isAll')
      isAllIpt.checked = isAll

      // 获取所有 checked为true 的商品
      let selectAll = productArr.filter(v => v.checked == true)

      // 算总数
      let countNum = selectAll.reduce((sum, v) => sum + v.pnum, 0)

      // 算总价
      let countPrice = selectAll.reduce((sum, v) => sum + v.pnum * v.pid.price, 0)

      console.log(countNum);
      console.log(countPrice);

      document.querySelector('#all-price').innerHTML = countPrice
      document.querySelector('#all-num').innerHTML = countNum

    }

    //删除商品 
    window.cartDelHandler = async function (cid) {
      console.log(cid);
      let r = await axios.delete(cartAPI + '/' + cid)
      console.log(r);
      showCartNum()
    }

    // 修改状态
    window.changeHandler = async function (cid, ipt) {
      console.log(cid);
      console.log(ipt.checked);
      let r = await axios.patch(cartAPI + '/' + cid, { checked: ipt.checked })
      showCartNum()
    }

    // 修改数量+
    window.cartAdd = async function (cid) {
      console.log(cid);
      console.log(productArr);

      // 找到数组中第一个满足条件的元素---条件v._id(元素的id)  和   cid 相等
      let cartObj = productArr.find(v => v._id === cid)
      console.log(cartObj);
      let currentNum = cartObj.pnum
      currentNum++;
      // 调用修改接口
      await axios.patch(cartAPI + '/' + cid, { pnum: currentNum })
      showCartNum()
    }

    // 修改数量-
    window.cartSub = async function (cid) {
      console.log(cid);
      console.log(productArr);

      // 找到数组中第一个满足条件的元素---条件v._id(元素的id)  和   cid 相等
      let cartObj = productArr.find(v => v._id === cid)
      console.log(cartObj);
      let currentNum = cartObj.pnum
      if (currentNum == 1) {
        return
      }
      currentNum--;
      // 调用修改接口
      await axios.patch(cartAPI + '/' + cid, { pnum: currentNum })
      showCartNum()
    }

    // 全选按钮
    window.allChangeHandler = function (ipt) {
      let checked = ipt.checked
      console.log(checked);
      // 遍历productArr  每遍历一次就发起一次请求
      console.log(productArr);

      // 循环遍历 把每一个 请求创建的promsie对象 都添加到 数组中
      let pArr = []
      productArr.forEach(v => {
        v._id;
        checked
        let p = axios.patch(cartAPI + '/' + v._id, { checked })
        pArr.push(p)
      })

      console.log(pArr);
      // 创建一个p0对象 状态依赖数组中 所有的promsie对象
      let p0 = Promise.all(pArr)
      p0.then(r => {
        showCartNum()
      })
    }

    // 清空购物车
    window.clearHandler = function () {
      // 循环遍历productArr 每遍历一次 都发起一次请求

      // productArr.forEach(v => {
      //     axios.delete(cartAPI + '/' + v._id).then(r=>{
      //         showCartNum()
      //     })
      // })

      let pArr = []
      productArr.forEach(v => {
        let p = axios.delete(cartAPI + '/' + v._id)
        pArr.push(p)
      })
      let p0 = Promise.all(pArr)
      p0.then(r => {
        showCartNum()
      })
    }

    // 删除所选
    window.delSelechHandler = function () {
      // 循环遍历productArr 每遍历一次 都发起一次请求

      // productArr.forEach(v => {
      //     axios.delete(cartAPI + '/' + v._id).then(r=>{
      //         showCartNum()
      //     })
      // })

      let pArr = []
      // 过滤出 所有选中
      productArr.filter(v => v.checked == true).forEach(v => {
        let p = axios.delete(cartAPI + '/' + v._id)
        pArr.push(p)
      })
      let p0 = Promise.all(pArr)
      p0.then(r => {
        showCartNum()
      })
    }

  </script>

</body>

</html>